"use strict";
var _jsonData = null;

function loadData() {
	chrome.runtime.sendMessage({name: "get-data"}, function(result) {
		var jsonStr = JSON.stringify(result.rootJson,undefined,2);
		$("#trashbin-data").val(jsonStr);
	});
}

function loadWhiteList() {
	chrome.runtime.sendMessage({name: "get-whitelist"}, function(result) {
		$("#whitelist-data").val(result.whitelist);
	});
}

function updateDescription() {
	_jsonData.description = $("#email-description").val();
	$("#email-code").text(JSON.stringify(_jsonData,undefined,2));
}

function loadEmail() {
	chrome.storage.local.get("capture",function(data) {
		if (!data.capture) {
			if ($("body").attr("data-tab") == "sendemail") {
				$("body").attr("data-tab","data");
			}
			$("select#sendemail-class").attr("selectedIndex","0");
			$("#tab-sendemail").css("display","none");
		} else {
			_jsonData = data.capture.jsonData;
			_jsonData.platform = "网站网页";
			updateDescription();
			$("body").attr("data-tab","sendemail");
			$("#tab-sendemail").css("display","");
			$("#email-screenshot").attr("src","data:" + data.capture.imageData);
		}
	});
}

function dataURItoBlob(dataURI) {
	var byteString = atob(dataURI.split(",")[1]);
	var mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];
	var ab = new ArrayBuffer(byteString.length);
	var ia = new Uint8Array(ab);

	for (var i=0; i<byteString.length; i++) {
		ia[i] = byteString.charCodeAt(i);
	}

	return new Blob([ab],{type:mimeString});
}

function getFormattedTime() {
	const now = new Date();

	const year = now.getFullYear();
	const month = ("0" + (now.getMonth() + 1)).slice(-2);
	const day = ("0" + now.getDate()).slice(-2);
	const hours = ("0" + now.getHours()).slice(-2);
	const minutes = ("0" + now.getMinutes()).slice(-2);
	const seconds = ("0" + now.getSeconds()).slice(-2);

	const formattedTime = year + month + day + hours + minutes + seconds;

	return formattedTime;
}

$(document).ready(function() {	
	chrome.storage.local.onChanged.addListener(function(changes) {
		if (changes.capture) {
			loadEmail();
		}
	});
	loadWhiteList();
	loadData();
	loadEmail();
	
	$.get(chrome.runtime.getURL("manifest.json"), function(info) {
		$("#trashbin-title").text(" 垃圾桶设置 " + info.version);
	});
	
	$("#tab-data").click(function(event) {
		$("body").attr("data-tab","data");
	});

	$("#tab-whitelist").click(function(event) {
		$("body").attr("data-tab","whitelist");
	});
	
	$("#tab-sendemail").click(function(event) {
		$("body").attr("data-tab","sendemail");
	});
	
	$("#trashbin-reload").click(function() {
		loadData();
	});
	
	$("#trashbin-save").click(function() {
		var jsonStr = $("#trashbin-data").val();
		var jsonObj = (jsonStr.trim() == "") ? null : JSON.parse(jsonStr);
		chrome.runtime.sendMessage({name: "set-data", data: jsonObj});
	});
	
	$("#trashbin-clear").click(function() {
		$("#trashbin-data").val("");
	});

	$("#trashbin-backup").click(function() {
		var file = new File([$("#trashbin-data").val()],"垃圾桶数据备份"+getFormattedTime()+".bak",{type: "text/plain;charset=utf-8"});
		saveAs(file);
	});

	$("#trashbin-restore").click(function() {
		$("#fileInput").change(function() {
			if (this.files.length === 0) {
				return;
			}
			const reader = new FileReader();
			reader.onload = function fileReadCompleted() {
				$("#trashbin-data").val(reader.result);
				$("#trashbin-save").click();
			}
			reader.readAsText(this.files[0],"utf-8");
		});
		$("#fileInput").click();
	});
	
	$("#whitelist-reload").click(function() {
		loadWhiteList();
	});
	
	$("#whitelist-save").click(function() {
		chrome.runtime.sendMessage({name: "set-whitelist", whitelist: $("#whitelist-data").val()});
	});
	
	$("#whitelist-clear").click(function() {
		$("#whitelist-data").val("");
	});
	
	$("#whitelist-backup").click(function() {
		var file = new File([$("#whitelist-data").val()],"垃圾桶白名单备份"+getFormattedTime()+".bak",{type: "text/plain;charset=utf-8"});
		saveAs(file);
	});

	$("#whitelist-restore").click(function() {
		$("#fileInput2").change(function() {
			if (this.files.length === 0) {
				return;
			}
			const reader = new FileReader();
			reader.onload = function fileReadCompleted() {
				$("#whitelist-data").val(reader.result);
				$("#whitelist-save").click();
			}
			reader.readAsText(this.files[0],"utf-8");
		});
		$("#fileInput2").click();
	});
	
	$("#sendemail-class").on("change", function() {
		$("#subject").text("我要举报: " + $("#sendemail-class").val());
	});

	$("#email-description").change(updateDescription);

	$("#email-description").on("input",updateDescription);

	function checkDescription() {
		var description = _jsonData.description;
		if (description == "") {
			alert("请填写举报描述!");
			$("#email-description").val("请输入举报内容描述(不能超过500个字符)").focus().select();
			updateDescription();
			return false;
		} else if (description == "请输入举报内容描述(不能超过500个字符)") {
			alert("请将举报描述修改为实际内容!");
			$("#email-description").focus().select();
			updateDescription();
			return false;
		}
		return true;
	}

	$("#sendemail-copy-send").click(function() {
		var subject = "我要举报: " + $("#sendemail-class").val();
		if (subject.indexOf("===") >= 0) {
			alert("请选择举报类别!");
			return;
		}

		if (!checkDescription()) {
			return;
		}
		
		try
		{
			// 复制图文内容;
			var node = document.getElementById("email-content");
			var sel = window.getSelection();
			sel.selectAllChildren(node);
			document.execCommand("copy");
		}
		catch (err)
		{
			// 复制文本内容;
			var node = document.getElementById("email-text");
			var sel = window.getSelection();
			sel.selectAllChildren(node);
			document.execCommand("copy");
		}
		
		window.location = "mailto:jubao@12377.cn?subject=" + subject;
	});

	$("#sendemail-copy-send-comp").click(function() {
		if (!checkDescription()) {
			return;
		}
		
		// 复制文本内容;
		var node = document.getElementById("email-text");
		var sel = window.getSelection();
		sel.selectAllChildren(node);
		document.execCommand("copy");
		
		window.location = "mailto:jubao@12377.cn";
	});
	
	$("#sendemail-clear").click(function() {
		chrome.storage.local.remove("capture");
	});

	$("#sendemail-save-screenshot").click(function() {
		var dataURI = $("#email-screenshot").attr("src");
		var blob = dataURItoBlob(dataURI);
		saveAs(blob,_jsonData.guid + ".png");
	});
});
